package com.westar.core.services;

import com.westar.base.model.AccountLimit;
import com.westar.base.util.DateTimeUtil;
import com.westar.core.dao.AccountLimitDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.List;

@Service
public class AccountLimitService {

    @Autowired
    AccountLimitDao accountLimitDao;

    @Autowired
    SystemLogService systemLogService;

    /**
     * 删除账号的限定
     * @param account
     */
    public void deleteAccountLimit(String account){
        //删除账号的限定
        accountLimitDao.delByField("accountLimit","account",account);
    }

    /**
     * 添加账号限定
     * @param account 账号
     * @param count 已有次数
     */
    public void addAccountLimit(String account,Integer count){
        //当前时间
        String nowTime = DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd_HH_mm);
        //过期时间30分钟后
        String limitTime = DateTimeUtil.addDate(nowTime,DateTimeUtil.yyyy_MM_dd_HH_mm, Calendar.MINUTE,30);

        AccountLimit accountLimit =  new AccountLimit();
        accountLimit.setAccount(account);
        if(count >=5){
            accountLimit.setLimitTime(limitTime);
            accountLimit.setMsg("已超过五次登录的密码错误！");
        }
        accountLimitDao.add(accountLimit);
    }

    /**
     * 查询账号的限定次数
     * @param account
     * @return
     */
    public int countAccountLimit(String account){
        int count = accountLimitDao.countAccountLimit(account);
        return count;
    }

    /**
     * 取得最近的数据
     * @param account
     * @return
     */
    public AccountLimit getRecentAccountLimit(String account){
        AccountLimit accountLimit = accountLimitDao.getRecentAccountLimit(account);
        return accountLimit;
    }

    /**
     * 查询需要移除的账号
     */
    public void removeAccountLimit() {
        List<AccountLimit> accountLimitList = accountLimitDao.listRecentAccountLimit();
        if(null!= accountLimitList && !accountLimitList.isEmpty()){
            //当前时间
            String nowTime = DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd_HH_mm);
            for (AccountLimit accountLimit : accountLimitList) {
                String limitTime = accountLimit.getLimitTime();
                //当前时间
                long timeA = DateTimeUtil.parseDate(nowTime, DateTimeUtil.yyyy_MM_dd_HH_mm).getTime();
                //预定的过期时间
                long timeB = DateTimeUtil.parseDate(limitTime, DateTimeUtil.yyyy_MM_dd_HH_mm).getTime();
                //账号封锁已过期，可以重新登录
                if(timeA > timeB){
                    String account = accountLimit.getAccount();
                    //解除封锁
                    this.deleteAccountLimit(account);

                    systemLogService.addSystemLog(account,"-","-1","解除密码错误限定五次！");
                }
            }
        }
    }
}
